<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单位" prop="unitName">
          <el-select
            v-model="queryParams.unitName"
            placeholder="请选择单位"
            style="width: 240px"
            clearable
            filterable
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.unitName"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="SN" prop="deviceCode">-->
        <!--          <el-input-->
        <!--            v-model="queryParams.deviceCode"-->
        <!--            placeholder="请输入SN"-->
        <!--            clearable-->
        <!--            @keyup.enter.native="handleQuery"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="unit-container">
      <div class="operation-container">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增设备
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="el-icon-refresh-left"-->
          <!--              size="mini"-->
          <!--              @click="handleBatchDisable"-->
          <!--              :disabled="multiple"-->
          <!--            >批量停用-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出数据
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>
      <!-- 设备卡片视图 -->
      <div style="overflow-y: auto;height: 55vh">
        <!-- 操作按钮区域 -->

        <div class="unit-list">
          <el-card
            v-for="item in filteredUnits"
            :key="item.id"
            class="unit-card"
            :class="{'has-warning': hasWarningDevices(item)}"
          >
            <div slot="header" class="unit-header">
              <div class="unit-info">
                <span class="unit-name">{{ item.unitName }}</span>
                <el-tag
                  size="mini"
                  effect="dark"
                  :type="getUnitStatusType(item)"
                  style="margin-left: 8px"
                >
                  {{ item.deviceList.length }}台设备
                </el-tag>
              </div>
            </div>

            <div class="device-detail">
              <div
                v-for="device in item.deviceList"
                :key="device.id"
                class="device-item"
                :class="getStatusClass(device.pushStatus)"
              >
                <div class="device-header">
                  <div class="device-name">
                    <dict-tag :options="dict.type.device_name" :value="device.deviceName"/>
                  </div>
                  <span :style="{ color: device.onlineType === 'success' ? '#13ce66' : '#e6a23c' }">
                    {{ device.onlineDeviceStatus }}
                  </span>
                  <el-tag
                    size="mini"
                    :type="getStatusTagType(device.pushStatus)"
                    effect="dark"
                  >
                    {{ getStatusText(device.pushStatus) }}
                  </el-tag>
                  <el-switch
                    v-model="device.deviceStatus"
                    active-color="#13ce66"
                    active-value="1"
                    inactive-value="0"
                    @change="handleUpdateDeviceStatus(device)"
                  />
                  <div class="device-value">
                    <i class="el-icon-odometer"></i>
                    <span>当前值:
                        <span v-if="device.latestValue" style="color: #4D84F3">{{ device.latestValue }}</span>
                        <span v-else>--</span>
                      </span>
                  </div>
                </div>
                <div class="device-footer">
                  <div class="device-info">
                    <span class="device-code">{{ device.deviceCode }}</span>
                  </div>
                  <el-button-group>
                    <el-tooltip content="动态数据同步" placement="top" v-if="device.deviceStatus === '1'&& device.pushStatus === '2'">
                      <el-button
                        size="mini"
                        icon="el-icon-sort"
                        @click="handleSynchronize(device)"
                      />
                    </el-tooltip>
                    <el-tooltip content="取消联网数据" placement="top" v-if="device.pushStatus === '2'">
                      <el-button
                        size="mini"
                        icon="el-icon-bottom"
                        @click="handleCancel(device)"
                        v-hasRole="['admin']"
                      />
                    </el-tooltip>
                    <el-tooltip content="推送数据" placement="top" v-if="device.pushStatus !== '2'">
                      <el-button
                        size="mini"
                        icon="el-icon-top"
                        @click="handlePush(device)"
                      />
                    </el-tooltip>
                    <el-tooltip content="编辑设备" placement="top">
                      <el-button
                        size="mini"
                        icon="el-icon-edit"
                        @click="handleUpdate(device)"
                      />
                    </el-tooltip>
                    <el-tooltip content="查看详情" placement="top">
                      <el-button
                        size="mini"
                        icon="el-icon-document"
                        @click="handleDetails(device)"
                      />
                    </el-tooltip>
                    <el-tooltip content="删除设备" placement="top" v-if="device.pushStatus !== '2'">
                      <el-button
                        size="mini"
                        icon="el-icon-delete"
                        @click="handleDelete(device)"
                        style="color: #ff0000;border: 1px solid #ff0000"
                        v-hasRole="['admin']"
                      />
                    </el-tooltip>
                  </el-button-group>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        :pageSizes="[9, 18, 27, 36]"
        @pagination="getList"
      />
    </div>

    <!-- 添加/编辑设备对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="850px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" inline>
        <el-form-item label="单位" prop="unitId">
          <el-select
            v-model="form.unitId"
            placeholder="请选择单位"
            class="form-item"
            clearable
            filterable
            @change="handleUnitChange"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备品类" prop="deviceCategory">
          <el-select
            v-model="form.deviceCategory"
            placeholder="请选择设备品类"
            class="form-item"
            clearable
            filterable
          >
            <el-option
              v-for="item in dict.type.device_category"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备名称" prop="deviceName">
          <el-select
            v-model="form.deviceName"
            placeholder="请选择设备名称"
            class="form-item"
            clearable
            filterable
          >
            <el-option
              v-for="item in dict.type.device_name"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="SN码" prop="deviceCode">
          <el-input
            v-model="form.deviceCode"
            placeholder="请输入SN码"
            class="form-item"
            clearable
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceTypeId">
          <el-select
            v-model="form.deviceTypeId"
            placeholder="请选择设备类型"
            class="form-item"
            clearable
            filterable
          >
            <el-option
              v-for="item in deviceTypeList"
              :key="item.id"
              :label="item.deviceTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="安装位置" prop="deviceAddress">
          <el-select
            v-model="form.deviceAddress"
            placeholder="请选择设备安装位置"
            class="form-item"
            clearable filterable
          >
            <el-option
              v-for="item in dict.type.device_address"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备状态" prop="deviceStatus">
          <el-switch
            v-model="form.deviceStatus"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item label="设备型号" prop="deviceModel">
          <el-input
            v-model="form.deviceModel"
            placeholder="请输入设备型号"
            class="form-item"
            clearable
          />
        </el-form-item>

        <el-row v-if="form.deviceCategory === '0'">
          <el-form-item label="阈值下限" prop="deviceMin">
            <el-input
              v-model="form.deviceMin"
              placeholder="请输入阈值下限"
              class="form-item"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="阈值上限" prop="deviceMax">
            <el-input
              v-model="form.deviceMax"
              placeholder="请输入阈值上限"
              class="form-item"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            :rows="3"
            class="form-item"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer
      title="设备详情"
      :visible.sync="drawerDevice"
      :direction="direction"
      size="60%"
      :before-close="handleClose"
    >
      <el-tabs v-model="activeName" type="card" class="tabs">
        <el-tab-pane label="设备信息" name="first">
          <div v-if="currentDevice" class="drawer-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="设备名称">
                <dict-tag :options="dict.type.device_name" :value="currentDevice.deviceName"/>
              </el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <el-tag
                  :type="getStatusTagType(currentDevice.pushStatus)"
                  style="margin-left: 10px"
                >
                  {{ getStatusText(currentDevice.pushStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="当前值">{{ currentDevice.latestValue || '--' }}</el-descriptions-item>
              <el-descriptions-item label="SN码">{{ currentDevice.deviceCode }}</el-descriptions-item>
              <el-descriptions-item label="设备类型">
                {{ getDeviceTypeName(currentDevice.deviceTypeId) }}
              </el-descriptions-item>
              <el-descriptions-item label="安装位置">
                <dict-tag :options="dict.type.device_address" :value="currentDevice.deviceAddress"/>
              </el-descriptions-item>
              <el-descriptions-item label="设备型号">{{ currentDevice.deviceModel || '--' }}</el-descriptions-item>
              <el-descriptions-item label="所属单位">{{ currentDevice.unitName }}</el-descriptions-item>
              <el-descriptions-item label="最后推送时间">{{ currentDevice.updateTime || '--' }}</el-descriptions-item>
              <el-descriptions-item label="备注">{{ currentDevice.remark || '--' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="设备数据" name="second">
          <div v-if="currentDevice" class="drawer-content">
            <el-table v-if="currentDevice.deviceCategory === '1'"
                      :data="deviceData"
                      border size="mini"
                      style="width: 100%">
              <el-table-column prop="sn" label="SN" width="300"></el-table-column>
              <el-table-column prop="hm" label="主机"></el-table-column>
              <el-table-column prop="time" label="时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="ps" label="数据"></el-table-column>
            </el-table>
            <el-table v-if="currentDevice.deviceCategory === '0'"
                      :data="deviceData"
                      border size="mini"
                      style="width: 100%">
              <el-table-column prop="sn" label="SN" width="200"></el-table-column>
              <el-table-column prop="time" label="时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="waterDeviceMessages" label="数据" width="300">
                <template slot-scope="scope">
                  <div v-for="item in scope.row.waterDeviceMessages">
                    <span>{{ item.device }} - {{ item.field1 }}- {{ item.field2 }}- {{ item.field3 }}- {{
                        item.field4
                      }}- {{ item.field5 }}- {{ item.field6 }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="csq" label="信号" width="120"></el-table-column>
              <el-table-column prop="vat" label="电压" width="120"></el-table-column>
              <el-table-column prop="imei" label="物联网卡号"></el-table-column>
            </el-table>
          </div>
          <pagination
            v-show="deviceDataTotal>0"
            :total="deviceDataTotal"
            :page.sync="deviceDataQuery.pageNum"
            :limit.sync="deviceDataQuery.pageSize"
            @pagination="getDeviceData"
          />
        </el-tab-pane>
      </el-tabs>

    </el-drawer>

    <el-dialog title="设备数据" :visible.sync="deviceDataOpen"
               width="500px"
               append-to-body
               :close-on-click-modal="false">
      <el-form ref="deviceDataForm" :model="deviceDataForm" :rules="deviceDataRules" label-width="120px">
        <el-form-item label="设备数据" prop="deviceValue">
          <el-input
            v-model="deviceDataForm.deviceValue"
            placeholder="请输入网关协议为事件，水协议为值"
            class="form-item"
            clearable
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeviceData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCardDevice,
  addDevice,
  delDevice,
  deviceId,
  devicePush,
  updateDevice,
  addDeviceValue,
  delDeviceId, gatewayUplinkData, waterUplinkData, OnlineStatus, dataOnlineStatus
} from "@/api/system/device";
import {listUnit} from "@/api/system/unit";
import {deviceTypeAllList} from "@/api/system/device";
import {parseTime} from "../../../utils/ruoyi";
import data from "@/views/system/dict/data.vue";
// import dict from "@/utils/dict/index";

export default {
  name: "Device",
  dicts: ['device_name', 'device_address', 'device_category',],
  data() {
    return {
      onlineStatusCache: new Map(),  // 缓存设备在线状态
      cacheExpire: 200* 1000, // 缓存有效期 30 秒
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备列表数据
      deviceList: [],
      // 当前查看的设备和单位
      currentDevice: null,
      activeName: 'first',
      deviceData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9,
      },
      deviceDataQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      deviceDataTotal: '0',
      // 状态选项
      statusOptions: [
        {value: '0', label: '离线'},
        {value: '1', label: '警告'},
        {value: '2', label: '正常'}
      ],
      // 表单参数
      form: {
        unitId: null,
        deviceName: null,
        deviceAddress: null,
        deviceTypeId: null,
        deviceCode: null,
        deviceStatus: '1',
        deviceCategory: null,
        deviceModel: null,
        deviceMax: null,
        deviceMin: null,
        remark: null
      },
      // 表单校验
      rules: {
        unitId: [
          {required: true, message: "单位不能为空", trigger: "blur"}
        ],
        deviceCategory: [
          {required: true, message: "设备品类不能为空", trigger: "blur"}
        ],
        deviceName: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        deviceAddress: [
          {required: true, message: "设备位置不能为空", trigger: "blur"}
        ],
        deviceTypeId: [
          {required: true, message: "设备类型不能为空", trigger: "blur"}
        ],
        deviceCode: [
          {required: true, message: "SN码不能为空", trigger: "blur"}
        ],
        deviceStatus: [
          {required: true, message: "设备状态不能为空", trigger: "blur"}
        ],
      },
      // 单位列表
      unitList: [],
      // 设备类型列表
      deviceTypeList: [],
      // 详情抽屉
      drawerDevice: false,
      direction: 'rtl',
      // 单位筛选
      unitFilter: '',
      // 展开的单位ID
      expandedUnitIds: [],
      deviceDataForm: [],
      deviceDataRules: {
        deviceValue: [
          {required: true, message: "设备数据不能为空", trigger: "blur"}
        ],
      },
      deviceDataOpen: false,
      deviceType: '',
    }
  },
  computed: {
    // 过滤后的单位列表
    filteredUnits() {
      return this.deviceList
        .filter(unit =>
          unit.unitName.toLowerCase().includes(this.unitFilter.toLowerCase())
        )
        .map(unit => ({
          ...unit,
          expanded: this.expandedUnitIds.includes(unit.id)
        }))
    }
  },
  created() {
    this.getList()
    this.getUnit()
    this.getDeviceTypeList()
  },
  mounted() {
    // 首次加载后立即获取状态（已在 getList 中调用）
    // 启动定时刷新（每30秒）
    // this.refreshTimer = setInterval(() => {
    //   this.fetchAllDeviceOnlineStatus();
    // }, this.cacheExpire);
  },

  beforeUnmount() {
    // 组件卸载时清除定时器，避免内存泄漏
    clearInterval(this.refreshTimer);
  },
  methods: {
    parseTime,
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listCardDevice(this.queryParams).then(response => {
        // 初始化设备列表时，为每个设备添加响应式在线状态字段
        this.deviceList = response.rows.map(unit => ({
          ...unit,
          deviceList: unit.deviceList.map(device => ({
            ...device,
            deviceStatus: String(device.deviceStatus),
            onlineDeviceStatus: '离线',  // 初始离线状态（响应式）
            onlineType: 'warning'   // 初始样式（警告）
          }))
        }));
        // this.fetchAllDeviceOnlineStatus();
        this.total = response.total;
        this.loading = false;
        // 调用获取在线状态（仅在getList时触发）
        this.fetchAllDeviceOnlineStatus();
      });
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        unitId: null,
        deviceName: null,
        deviceAddress: null,
        deviceTypeId: null,
        deviceCode: null,
        deviceStatus: '1',
        deviceCategory: null,
        deviceModel: null,
        deviceMax: null,
        deviceMin: null,
        remark: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加设备信息"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      deviceId(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改设备信息"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    // 修改设备状态
    handleUpdateDeviceStatus(row) {
      updateDevice({
        ...row,
        deviceStatus: row.deviceStatus
      }).then(response => {
        this.$modal.msgSuccess("修改成功")
        this.getList()
      })
    },

    /** 批量停用 */
    handleBatchDisable() {
      const deviceIds = this.ids.join(",")
      this.$modal.confirm('确认要停用选中的设备吗？').then(() => {
        return updateDevice({
          ids: deviceIds,
          deviceStatus: '0'
        })
      }).then(() => {
        this.$modal.msgSuccess("操作成功")
        this.getList()
      }).catch(() => {
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(() => {
        return delDevice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },

    /** 查询单位 */
    getUnit() {
      listUnit({
        pageNum: 1,
        pageSize: 999999,
      }).then(response => {
        this.unitList = response.rows
      })
    },

    /** 设备类型 */
    getDeviceTypeList() {
      deviceTypeAllList().then(response => {
        this.deviceTypeList = response.data
      })
    },

    // 获取设备类型名称
    getDeviceTypeName(id) {
      const type = this.deviceTypeList.find(item => item.id === id)
      return type ? type.deviceTypeName : '--'
    },

    // 详情
    handleDetails(row) {
      this.activeName = 'first'
      this.drawerDevice = true
      const id = row.id || this.ids
      deviceId(id).then(response => {
        this.currentDevice = {
          ...response.data,
          unitName: this.unitList.find(u => u.id === response.data.unitId)?.unitName || '--'
        }
        this.getDeviceData()
      })
    },
    getDeviceData() {
      this.deviceDataQuery.deviceNo = this.currentDevice.deviceCode
      if (this.currentDevice.deviceCategory === '0') {
        waterUplinkData(this.deviceDataQuery).then(response => {
          this.deviceData = response?.data?.records
          this.deviceDataTotal = response?.data?.total
        })
      } else {
        gatewayUplinkData(this.deviceDataQuery).then(response => {
          this.deviceData = response?.data?.records
          this.deviceDataTotal = response?.data?.total
        })
      }

    },
    handleClose(done) {
      done();
    },

    // 推送
    handlePush(val) {
      this.$modal.confirm('确认要推送设备数据吗？').then(() => {
        devicePush(val.id).then(response => {
          this.$modal.msgSuccess("推送成功！")
          this.getList()
        })
      }).catch(() => {
      })
    },
    /** 取消推送按钮操作 */
    handleCancel(row) {
      const deviceId = row.id
      delDeviceId(deviceId).then(response => {
        this.$modal.msgSuccess("取消推送成功！")
        this.getList()
      })
    },
    /** 同步数据 */
    handleSynchronize(row) {
      this.deviceDataOpen = true
      this.deviceDataForm = row
    },
    /** 确定同步数据 */
    submitDeviceData(row) {
      this.deviceDataOpen = true
      console.log(this.deviceDataForm.id, this.deviceDataForm.deviceValue)
      // const id = row.id
      addDeviceValue(this.deviceDataForm.id, this.deviceDataForm.deviceValue).then(response => {
        this.$modal.msgSuccess("同步成功！")
        this.getList()
        this.deviceDataOpen = false
        this.deviceDataForm = {}
      })
    },


    // 单位是否有警告设备
    hasWarningDevices(unit) {
      return unit.deviceList.some(d => d.pushStatus === '1')
    },

    // 获取单位状态类型
    getUnitStatusType(unit) {
      if (unit.deviceList.some(d => d.pushStatus === '0')) return 'danger'
      if (unit.deviceList.some(d => d.pushStatus === '1')) return 'warning'
      return 'success'
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case '0':
          return 'danger'
        case '1':
          return 'warning'
        case '2':
          return 'success'
        default:
          return ''
      }
    },


    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case '0':
          return '未推送'
        case '1':
          return '推送失败'
        case '2':
          return '推送成功'
        default:
          return '未知'
      }
    },

    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case '0':
          return 'status-inactive'
        case '1':
          return 'status-warning'
        case '2':
          return 'status-active'
        default:
          return ''
      }
    },
    // 获取状态标签类型
    getOnlineStatusTagType(status) {
      switch (status) {
        case '0':
          return 'warning'
        case '1':
          return 'success'
        default:
          return ''
      }
    },

    // 批量获取所有设备的在线状态（仅在getList时调用）
    fetchAllDeviceOnlineStatus() {
      this.deviceList.forEach(unit => {
        unit.deviceList.forEach(device => {
          this.fetchDeviceOnlineStatus(device);
        });
      });
    },

    // 获取单个设备的在线状态（带缓存）
    async fetchDeviceOnlineStatus(device) {
      const { deviceCode, deviceName } = device;
      try {
        let isOnline;
        // 根据设备类型调用不同接口
        if (deviceName !== '4') {
          const response = await OnlineStatus(deviceCode);
          isOnline = response;
        } else {
          const response = await dataOnlineStatus(deviceCode);
          isOnline = response.data;
        }
        // 更新设备状态（响应式触发视图更新）
        device.onlineDeviceStatus = isOnline ? '在线' : '离线';
        device.onlineType = isOnline ? 'success' : 'warning';
      } catch (error) {
        // 接口失败时保持默认状态
        device.onlineDeviceStatus = '离线';
        device.onlineType = 'warning';
      }
    },

    // 单位改变处理
    handleUnitChange(unitId) {
      const unit = this.unitList.find(u => u.id === unitId)
      if (unit) {
        this.form.unitAddress = unit.unitAddress
      }
    }
  }
}
</script>

<style scoped lang="scss">
.form-item {
  width: 250px;
}

.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 搜索区域 */
.search-container {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 操作按钮区域 */
.operation-container {
  background-color: #fff;
  padding: 15px 20px;
  //margin-bottom: 15px;
  border-radius: 4px;
  //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 单位容器 */
.unit-container {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  //margin-bottom: 15px;
}

.unit-filter {
  margin-bottom: 16px;
}

/* 单位列表 */
.unit-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
  gap: 16px;
}

/* 单位卡片 */
.unit-card {
  border-radius: 8px;
  transition: all 0.3s;
  //margin-bottom: 16px;

  &.has-warning {
    border-top: 2px solid #e6a23c;
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.unit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  //padding: 12px 16px;
  //
  .unit-info {
    display: flex;
    align-items: center;

    .el-icon-location-outline {
      margin-right: 8px;
      color: #909399;
    }

    .unit-name {
      font-weight: 500;
    }
  }

  .unit-actions {
    .el-button {
      padding: 4px;
      margin-left: 6px;
    }
  }
}

/* 设备详情 */
.device-detail {
  //padding: 16px;
}

/* 设备项 */
.device-item {
  padding: 5px;
  margin-bottom: 4px;
  border-radius: 6px;
  //background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  }

  &.status-inactive {
    border-left: 3px solid #909399;
  }

  &.status-warning {
    border-left: 3px solid #e6a23c;
  }

  &.status-active {
    border-left: 3px solid #67c23a;
  }
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.device-name {
}

.device-body {
  //display: flex;
  //justify-content: space-between;
  //align-items: center;
  margin: 8px 0;

  .device-value {
    //display: flex;
    //align-items: center;
    font-size: 12px;
    color: #666;

    i {
      margin-right: 5px;
    }
  }
}

.device-footer {
  display: flex;
  justify-content: space-between;

  .el-button-group {
    .el-button {
      padding: 5px;
      margin-left: 10px;
    }
  }
}

/* 分页区域 */
.pagination-container {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 抽屉内容 */
.drawer-content {
  padding: 20px;

  .el-descriptions {
    margin-bottom: 20px;
  }

  .drawer-footer {
    text-align: right;
    margin-top: 20px;

    .el-button + .el-button {
      margin-left: 10px;
    }
  }
}
</style>

<style lang="scss">
/* 对话框全局样式 */
.el-dialog {
  border-radius: 8px;

  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
  }
}

.el-drawer {
  .el-drawer__header {
    margin-bottom: 20px;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .el-drawer__body {
    padding: 0 20px 20px;
  }
}
</style>
